package com.example.demo;

/**
 * 农历（阴历）↔ 公历转换
 */
public class LunarConverter {

    // 平均朔望月（天）
    static final double SYNODIC_MONTH = 29.530588853;

    /**
     * 在 jd 附近找到最近的新月（朔）儒略日，返回 JD（UTC）
     * 使用粗略网格搜索 + 细化
     */
    public static double getNewMoonNearJD(double jdApprox) {
        double bestJD = jdApprox;
        double bestVal = Double.MAX_VALUE;
        // 先粗网格搜索 +-2 天
        for (double jd = jdApprox - 2.0; jd <= jdApprox + 2.0; jd += 0.5) {
            double val = Math.abs(solarMoonElongation(jd));
            if (val < bestVal) { bestVal = val; bestJD = jd; }
        }
        // 细化（二分/缩小区间）
        double left = bestJD - 0.5;
        double right = bestJD + 0.5;
        for (int i = 0; i < 60; i++) {
            double m = (left + right) / 2.0;
            double fm = Math.abs(solarMoonElongation(m));
            double fl = Math.abs(solarMoonElongation(left));
            double fr = Math.abs(solarMoonElongation(right));
            if (fm <= fl && fm <= fr) { left = m - (right-left)/4.0; right = m + (right-left)/4.0; bestJD = m; }
            else if (fl < fr) { right = m; }
            else { left = m; }
            if ((right - left) < 1.0/1440.0) break; // 到分级精度
        }
        return bestJD;
    }
}
